import React, { useState, useEffect } from 'react'
import { Button, Input, Icon } from '@alifd/next'
import { translate } from '@/utils/tools'
import styles from './index.module.scss'

const EntityTitleDom = ({ name, fatherId, arr, treeKey, updateBIMName, idToEye, treeType, onlyToEye, setEye }) => {
  const [opacity, setOpacity] = useState('0')
  const [mouse, setMouse] = useState(false)
  const [click, setClick] = useState(false)
  const [value, setValue] = useState('')

  useEffect(() => setValue(name ? translate(name || fatherId) : fatherId), [name, fatherId])

  useEffect(() => {
    setOpacity(
      arr.find(i => onlyToEye.ids.includes(i.id)) || arr.find(i => idToEye.ids.includes(i.id)) || mouse ? '1' : '0'
    )
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [mouse, onlyToEye, idToEye, treeKey])

  const onBlur = () => {
    setClick(false)
    updateBIMName(value)
  }

  return (
    <div
      className={styles.titleDom}
      onMouseEnter={e => {
        setMouse(true)
        e.preventDefault()
      }}
      onMouseLeave={e => {
        setMouse(false)
        e.preventDefault()
      }}
    >
      <div
        style={{ width: !click ? 'auto' : '150px' }}
        onDoubleClick={e => {
          if (!click) setClick(true)
          e.preventDefault()
        }}
      >
        {click && treeType === 'bim' ? (
          <Input
            hasClear
            trim
            onBlur={onBlur}
            onChange={val => setValue(val)}
            autoFocus
            defaultValue={value}
            style={{ width: '100%' }}
            size="small"
          />
        ) : (
          value
        )}
      </div>
      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      <Button
        className={styles.button}
        style={{ opacity: opacity }}
        ghost="dark"
        type="normal"
        text
        onClick={() => setEye({ treeKey, type: 'idToEye' })}
      >
        {!arr.find(i => idToEye.ids.includes(i.id)) ? (
          <Icon className={styles.icon} type="eye" style={{ color: '#f5f5f5' }} />
        ) : (
          <Icon className={styles.icon} type="eye-close" style={{ color: '#1890ff' }} />
        )}
      </Button>
      &nbsp;&nbsp;
      <Button
        className={styles.button}
        style={{ opacity: opacity }}
        ghost="dark"
        type="normal"
        text
        onClick={() => setEye({ treeKey, type: 'onlyToEye' })}
      >
        {!arr.find(i => onlyToEye.ids.includes(i.id)) ? (
          <Icon className={styles.icon} type="favorites-filling" style={{ color: '#f5f5f5' }} />
        ) : (
          <Icon className={styles.icon} type="favorites-filling" style={{ color: '#1890ff' }} />
        )}
      </Button>
    </div>
  )
}

export default EntityTitleDom
